// 弹出窗口，支持拖曳，改变大小，关闭，最大化，最小化
desktop.win = {
	winHtml : function(title, url, id) {
		return "<div class='windows corner' id=" + id + "><div class='win_title' onselectstart='return false;'><b>" + title + "</b><span class='win_btnblock'><a href='#' class='winMinimize' title='最小化'></a><a href='#' class='winMaximize' title='最大化'></a><a href='#' class='winHyimize' title='还原'></a><a href='#' class='winRefresh' title='刷新'></a><a href='#' class='winClose' title='关闭'></a></span></div>" + "<iframe frameborder='0' name='myFrame_" + id + "' id='myFrame_" + id
				+ "' class='winframe' scrolling='auto' width='100%' src=''></iframe>" + "</div>";
	},
	// 添加遮障层，修复iframe 鼠标经过事件bug
	iframFix : function(obj) {
		obj.each(function() {
			var o = $(this);
			o.find('iframe').hide();

		});
	},
	// 获取当前窗口最大的z-index值
	maxWinZindex : function($win) {
		return Math.max.apply(null, $.map($win, function(e, n) {
			if ($(e).css('position') == 'absolute')
				return parseInt($(e).css('z-index')) || 1;
		}));
	},
	// 获取当前最顶层窗口
	findTopWin : function($win, maxZ) {
		var topWin;
		$win.each(function(index) {
			if ($(this).css("z-index") == maxZ) {
				topWin = $(this);
				return false;
			}
		});
		return topWin;
	},
	// 关闭窗口
	close : function(obj) {
		var me = this, $win = $('div.windows').not(":hidden"), maxZ, topWin;
		desktop.taskbar.delWinTab(obj);
		obj.hide(200, function() {
			$(this).remove();
		});
		$('.mask').hide();
		// 当关闭窗口后寻找最大z-index的窗口并使其出入选择状态
		if ($win.size() > 1) {
			maxZ = me.maxWinZindex($win.not(obj));
			topWin = me.findTopWin($win, maxZ);
			me.switchZindex(topWin);
		}

		return false;
	},
	// 最小化窗口
	minimize : function(obj) {
		var me = this, $win = $('div.windows').not(":hidden"), maxZ, topWin, objTab;
		obj.hide();
		// 最小化窗口后，寻找最大z-index窗口至顶
		if ($win.size() > 1) {
			maxZ = me.maxWinZindex($win.not(obj));
			topWin = me.findTopWin($win, maxZ);
			me.switchZindex(topWin);
			obj.hide();
		} else {
			objTab = desktop.taskbar.findWinTab(obj);
			objTab.removeClass('selectTab').addClass('defaultTab');
		}
	},
	// 最大化窗口函数
	maximize : function(obj) {
		var myData = desktop.getMydata(), wh = myData.winWh; // 获取当前document宽高
		obj.css({
			'width' : wh['w'],
			'height' : wh['h'],
			'left' : 0,
			'top' : 0
		}).draggable("disable").resizable("disable").fadeTo("fast", 1).find(".winframe").css({
			'width' : wh['w'],
			'height' : wh['h'] - 26
		});

	},
	// 还原窗口函数
	restore : function(obj) {
		var myData = obj.data(), winLocation = myData.winLocation; // 获取窗口最大化前的位置大小
		obj.css({
			'width' : winLocation['w'],
			'height' : winLocation['h'],
			'left' : winLocation['left'],
			'top' : winLocation['top']
		}).draggable("enable").resizable("enable").find(".winframe").css({
			'width' : winLocation['w'],
			'height' : winLocation['h'] - 26
		});
	},
	// 交换窗口z-index值
	switchZindex : function(obj) {
		var myData = desktop.getMydata(), $topWin = myData.topWin, $topWinTab = myData.topWinTab, curWinZindex = obj.css("z-index"), maxZ = myData.maxZindex, objTab = desktop.taskbar.findWinTab(obj);

		if (!$topWin.is(obj)) {

			obj.css("z-index", maxZ);
			objTab.removeClass('defaultTab').addClass('selectTab');

			$topWin.css("z-index", curWinZindex);
			$topWinTab.removeClass('selectTab').addClass('defaultTab');
			// 更新最顶层窗口对象
			$('body').data("topWin", obj).data("topWinTab", objTab);
		}
	},
	// 新建一个窗口
	newWin : function(options) {
		var myData = desktop.getMydata(), wh = myData.winWh,
		// 获取当前document宽高
		$windows = $("div.windows"), me = this, curwinNum = (typeof (myData.winNum) == "Number") ? myData.winNum : 0; // 判断当前已有多少窗口

		// 默认参数配置
		var defaults = {
			title : null,
			id : null,
			// width : Math.round(wh['w'] * 0.6),
			width : isperp.appConfig.windowSize["big"][0] + 50,
			/* Only pixels */
			// height : Math.round(wh['h'] * 0.8),
			height : isperp.appConfig.windowSize["big"][1] + 50,
			/* Only pixels */
			minWidth : 250,
			/* Only pixels */
			minHeight : 250,
			/* Only pixels */
			src : null,
			/* 框架的src路径 */
			resizable : true,
			/* true, false */
			maximizable : true,
			/* true, false */
			minimizable : true,
			/* true, false */
			closable : true,
			/* true, false */
			draggable : true,
			/* true, false */
			status : 'regular',
			/* 'regular', 'maximized', 'minimized' */
			animationSpeed : 500,
			animation : true,
			modal : false
		// 如果true则遮罩整个界面
		};
		var options = $.extend(defaults, options);
		// 判断窗口位置，否则使用默认值
		// var dxy = Math.floor((Math.random() * 100)) + 30;
		var wLeft = (wh['w'] - options['width']) / 2;
		var wTop = (wh['h'] - options['height']) / 2;

		// 给窗口赋予新的z-index值
		var zindex = curwinNum + 100;
		var id = "myWin_" + options['id']; // 根据传来的id将作为新窗口id
		$('body').data("winNum", curwinNum + 1); // 更新窗口数量

		// 判断如果此id的窗口存在，则不创建窗口
		if ($("#" + id).size() <= 0) {
			// 在任务栏里添加tab
			desktop.taskbar.addWinTab(options['title'], options['id']);

			$(me.winHtml(options['title'], options['src'], id)).appendTo('body');
			var $newWin = $("#" + id), $icon = $("#" + options['id']), $iconOffset = $icon.offset(), winMaximize_btn = $newWin.find('a.winMaximize'), winMinimize_btn = $newWin.find('a.winMinimize'), winClose_btn = $newWin.find('a.winClose'), winRestore_btn = $newWin.find('a.winHyimize'), winTitle = $newWin.find('div.win_title'), winRefresh_btn = $newWin.find('a.winRefresh');
			$newWin.find('.win_title b').html('正在加载:' + options.title);
			winRestore_btn.hide();
			if (!options['maximizable'])
				winMaximize_btn.hide();
			if (!options['minimizable'])
				winMinimize_btn.hide();
			if (!options['closable'])
				winClose_btn.hide();
			winTitle.dblclick(function(event) {
				event.stopPropagation();
				if (options.maximizable === true) {
					if (options.status == "maximized") {
						me.restore($newWin);
						winRestore_btn.hide();
						winMaximize_btn.show();
						options.status = "regular";
					} else {
						me.maximize($newWin);
						winMaximize_btn.hide();
						winRestore_btn.show();
						options.status = "maximized";
					}
				}
			});

			// 存储窗口最大的z-index值,及最顶层窗口对象
			$('body').data({
				"maxZindex" : zindex,
				"topWin" : $newWin
			});

			$(window).wresize(function() {
				if (options.status == 'regular') {
					$newWin.css({
						"left" : ($(window).width() - parseInt($newWin.css('width').replace('px', ''))) / 2,
						"top" : ($(window).height() - parseInt($newWin.css('height').replace('px', ''))) / 2
					});
				}

			});
			// 判断窗口是否启用动画效果
			if (options.animation) {
				$newWin.css({
					"left" : options['query'] ? 70 : $iconOffset.left,
					"top" : options['query'] ? 70 : $iconOffset.left,
					"z-index" : zindex
				}).addClass("loading").show().animate({
					width : options['width'],
					height : options['height'],
					top : wTop,
					left : wLeft
				}, 200, function() {
					$(this).find(".winframe").attr("src", options['src']).load(function() {
						$newWin.find('.win_title b').html(options.title);
					});
				});
			} else {
				$newWin.css({
					"width" : options['width'],
					"height" : options['height'],
					"left" : wLeft,
					"top" : wTop,
					"z-index" : zindex
				}).addClass("loading").show(10, function() {
					$(this).find(".winframe").attr("src", options['src']).load(function() {
						$newWin.find('.win_title b').html(options.title);
					});
				});
			}

			$newWin.data('winLocation', {
				'w' : options['width'],
				'h' : options['height'],
				'left' : wLeft,
				'top' : wTop
			})
			// 鼠标点击，切换窗口，使此窗口显示到最上面
			.bind({
				"mousedown" : function(event) {
					me.switchZindex($(this));
				},
				"mouseup" : function() {
					$(this).find('.zzDiv').remove();
				}
			}).find(".winframe").css({
				"width" : options['width'],
				"height" : options['height'] - 26
			});

			// 调用窗口拖动,参数可拖动的范围上下左右，窗口id和，浏览器可视窗口大小
			if (options['draggable']) {
				me.drag([ 0, 0, wh['w'] - options['width'] - 10, wh['h'] - options['height'] - 35 ], $newWin, wh);
			}
			// 调用窗口resize,传递最大最小宽度和高度，新窗口对象id，浏览器可视窗口大小
			if (options['resizable']) {
				me.resize(options['minWidth'], options['minHeight'], wh['w'] - wLeft, wh['h'] - wTop - 35, $newWin, wh);
			}

			// 窗口最大化，最小化，及关闭
			winClose_btn.click(function(event) {
				event.stopPropagation();
				me.close($newWin);
				return false;
			});
			winRefresh_btn.click(function(event) {
				event.stopPropagation();

				$newWin.find("iframe").each(function(index, item) {
					$(item).attr("src", $(item).attr("src"));

				});

				return false;
			});
			// 最大化
			winMaximize_btn.click(function(event) {
				event.stopPropagation();
				if (options['status'] == "regular") {
					me.maximize($newWin);
					$(this).hide();
					winRestore_btn.show();
					options['status'] = "maximized";
				}
				return false;
			});

			// 如果浏览器窗口大小改变，则更新窗口大小
			$(window).wresize(function() {
				if (options['status'] == "maximized") {
					me.maximize($newWin);
				}
			});
			// 还原窗口
			winRestore_btn.click(function(event) {
				event.stopPropagation();
				if (options['status'] == "maximized") {
					me.restore($newWin);
					$(this).hide();
					winMaximize_btn.show();
					options['status'] = "regular";
					if (options.modal === true) {
						$('.mask').show();
					}
				}
				return false;
			});
			// 最小化窗口
			winMinimize_btn.click(function() {
				me.minimize($newWin);
				if (options.modal === true) {
					$('.mask').hide();
				}
				return false;
			});
		} else {

			// 如果已存在此窗口，判断是否隐藏
			var wins = $("#" + id), objTab = desktop.taskbar.findWinTab(wins);
			if (wins.is(":hidden")) {
				wins.show();
				objTab.removeClass('defaultTab').addClass('selectTab'); // 当只有一个窗口时
				desktop.win.switchZindex(wins);
			} else {

			}
		}
		if (options.modal === true) {
			$('.mask').show();
		}
	},
	upWinResize_block : function(win) {

		// 更新窗口可改变大小范围,wh为浏览器窗口大小
		var offset = win.offset();
		win.resizable("option", {
			'maxWidth' : $(window).width() - offset.left - 10,
			'maxHeight' : $(window).height() - offset.top - 35
		});
	},
	drag : function(arr, $newWin, wh) {
		var me = this;
		$newWin.draggable({
			handle : 'div.win_title',
			iframeFix : false,
			scroll : false
		}).bind("dragstart", function(event, ui) {
			me.iframFix($(this));
		}).bind("dragstop", function(event, ui) {
			var objme = $(this);
			var offset = objme.offset();
			// 计算可拖曳范围
			me.upWinResize_block(objme);
			objme.find('iframe').show();
			objme.data('winLocation', {
				'w' : objme.width(),
				'h' : objme.height(),
				'left' : offset.left,
				'top' : offset.top
			}).find('.zzDiv').remove();

			if (event.pageY > wh.h - 10) {
				$(this).css("top", wh.h - 30);
			}
		});

		$("div.win_title").css("cursor", "move");
	},
	resize : function(minW, minH, maxW, maxH, $newWin, wh) {
		var me = this;
		$newWin.resizable({
			minHeight : minH,
			minWidth : minW,
			containment : 'document',
			maxWidth : maxW,
			maxHeight : maxH
		}).css("position", "absolute").bind("resize", function(event, ui) {
			var h = $(this).innerHeight(), w = $(this).innerWidth();

			// 拖曳改变窗口大小，更新iframe宽度和高度，并显示iframe
			$(this).children(".winframe").css({
				"width" : w,
				"height" : h - 26
			});

		}).bind("resizestop", function(event, ui) {
			var objme = $(this);
			var offset = objme.offset();
			var h = objme.innerHeight(), w = objme.innerWidth();

			objme.data('winLocation', {
				'w' : w,
				'h' : h,
				'left' : offset.left,
				'top' : offset.top
			})
			// 删除遮障iframe的层
			.find(".zzDiv").remove();
		});
	}
};